<?php
namespace app\controllers;

use fastphp\base\Controller;
use app\models\Problem;
use app\models\Error;
use app\models\User;

class ProblemController extends Controller
{
    public function index()
    {
        $this->assign('title', '题目列表');
        $this->assign('list', (new Problem())->list(is_numeric(@$_GET['page'])?@$_GET['page']:1, 20, false, isset($_GET['category'])?@$_GET['category']:'oj'));
        $this->render();
    }
    public function show($id = null)
    {
        if ($id === null || !($problem = (new Problem())->get($id))) {
            Error::error(404);
        }
        $this->assign('title', $problem['name']);
        $this->assign('problem', (new Problem())->analyse($problem));
        $this->render();
    }
    public function create()
    {
        if (!User::isLogin()) Error::error(403);
        if (!empty($_POST['name']) && !empty($_POST['content'])) {
            $pid = (int)((new Problem())->where(['`category`="oj"'])->order(['`id` DESC'])->fetch()['id'])+1;
            $res = (new Problem())->add(['id'=>$pid, 'name'=>$_POST['name'], 'content'=>$_POST['content'], 'author'=>User::getUser()['id']]);
            exit(header('Location: /problem/show/' . $pid));
        }
        $this->assign('title', '新建题目');
        $this->render();
    }
}